
/**
 * 玩家业务模块
 * 处理登录，玩家数据持久化。
 * 可以考虑把事件上报队列放这里。
 */

import NativeHelper from "../comm/NativeHelper";
import Cfgs from "../configs/Cfgs";
import ADCtrl from "../ctrl/ADCtrl";
import TDCtrl from "../ctrl/TDCtrl";
import { EventName } from "../manager/EventMgr";
import { EventMgr } from "../manager/EventMgr";
import { ABTest } from "../net/ABTest";
import { EventReport, ReportDataLogin } from "../net/EventReport";
import HttpApi from "../net/HttpApi";
import MyFetch from "../net/MyFetch";
import { GameConfig, LoginTypeID } from "./GameConfig";
import LocalValues from "./LocalValues";
import UserModel from "./UserModel";

class UserCtrl {
    // 服务端sessionId
    private sessionId: string;
    private timeoutLogin: any;
    private _reportLevel = 0;
    private _loginData: LoginData;
    private _bFirst: boolean;
    public get reportLevel() {
        return this._reportLevel || UserModel.curLevelId;
    }
    public set reportLevel(level: number) {
        this._reportLevel = level;
    }

    public init() {
        this._bFirst = !LocalValues.getUserData();
        this.listenEvents();
    }
    private listenEvents() {
        EventMgr.on(EventName.onNetState, this.onNetState, this);
        EventMgr.on(EventName.onCurLevelChange, this.onLevelChange, this);
    }
    private onNetState(bool: boolean) {
        if (bool && !this.isLogin) {
            this.retryLogin();
        }
    }
    private onLevelChange(now: number, old: number) {
    }

    public async login() {
        clearTimeout(this.timeoutLogin);
        if (this.isLogin) {
            return;
        }
        if (!NativeHelper.deviceId) {
            this.retryLogin(1);
            return;
        }
        let deviceId = LocalValues.getString('deviceId');
        if (!deviceId) {
            deviceId = NativeHelper.deviceId + Math.random().toString(36).substring(2, 10);
        }
        // console.log('deviceId', deviceId);
        HttpApi.login({
            openId: deviceId, // 设备id
            platform: LoginTypeID.Guest,
            token: '',
            version: 0
        }).then(res=>{
            console.log('### HttpApi.login res:',res);
            if (res?.code == 0) {
                LocalValues.setString('deviceId', deviceId);
                this.onLogin(res.data);
            } else {
                this.retryLogin();
            }
        }).catch(err=>{
            console.log('### HttpApi.login err:',err);
            this.retryLogin();
        });
        if (UserModel.uid) {
            NativeHelper.callAdUserId(UserModel.uid.toString());
        }
    }

    private retryLogin(sec = 30) {
        clearTimeout(this.timeoutLogin);
        this.timeoutLogin = setTimeout(() => {
            this.login();
        }, sec * 1000); // 每30s尝试一次登录
    }

    private onLogin(data: LoginData) {
        console.log('###登录成功###', data);
        this._loginData = data;
        this.sessionId = data.sessionId;
        UserModel.uid = data.uid;
        TDCtrl.instance.onLogin(data);
        MyFetch.setSessionId(this.sessionId);
        // 开始上报打点队列
        EventReport.init(data.uid.toString(), GameConfig.reportApiKey, NativeHelper.adjustAdid);
        ABTest.init({uid: data.uid.toString(), apiKey: GameConfig.reportApiKey});
        if (this._bFirst) {
            this.reportRegister();
        }
        this.reportLogin();
        NativeHelper.callAdUserId(UserModel.uid.toString());
    }

    public get isLogin() {
        return !!this.sessionId;
    }


    //========上报打点========
    public reportRegister() {
        if (NativeHelper.systemInfo) {
            // EventReport.register({});
        } else {
            console.error('### reportRegister NativeHelper.systemInfo is null');
        }
    }
    public reportLogin() {
        const data: ReportDataLogin = {
            fbid: '',
            email: '',
            deviceToken: NativeHelper.firebaseToken,
            level: this.reportLevel,
            ip: this._loginData?.loginIp || '',
        };
        EventReport.login(data);
    }
    //=======================
}

export default new UserCtrl();


export interface LoginData {
    openId: string;
    loginType: number;
    regTime: number;
    sessionId: string;
    uid: number;
    loginIp: string;
}
